import { addSpaceUsingPost } from '@/services/backend/spaceController';
import { ProForm } from '@ant-design/pro-components';
import '@umijs/max';
import { message, Modal, Select } from 'antd';
import React, { useEffect, useState } from 'react';
import {addSpaceUserUsingPost, getCanAddUsersUsingPost} from '@/services/backend/spaceUserController';
import {SPACE_ROLE_OPTIONS, SPACE_TYPE_OPTIONS} from "@/constants/space";

const { Option } = Select;

interface Props {
  visible: boolean;
  spaceId?: number;
  onSubmit?: (values: API.SpaceUserAddRequest) => void;
  onCancel?: () => void;
}

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.SpaceAddRequest) => {
  const hide = message.loading('正在添加');
  try {
    await addSpaceUsingPost({
      ...fields,
      spaceLevel: 0,
    });
    hide();
    message.success('创建成功');
    return true;
  } catch (error: any) {
    hide();
    message.error('创建失败，' + error.message);
    return false;
  }
};

/**
 * 创建弹窗
 * @param props
 * @constructor
 */
const AddUserToSpaceModal: React.FC<Props> = (props) => {
  const { visible, spaceId, onSubmit, onCancel } = props;
  const [form] = ProForm.useForm();
  const [users, setUsers] = useState<API.UserVO[]>();
  useEffect(() => {
    const initData = async () => {
      const res = await getCanAddUsersUsingPost({
        spaceId: spaceId,
      });
      setUsers(res.data);
    };
    initData();
  }, []);
  return (
    <Modal
      destroyOnClose
      closable={false}
      title={'添加协作人'}
      open={visible}
      footer={null}
      onCancel={() => {
        onCancel?.();
      }}
    >
      <div>
        <ProForm<API.SpaceUserAddRequest>
          form={form}
          onValuesChange={console.log}
          initialValues={
            {
              spaceId: spaceId,
              spaceRole: SPACE_ROLE_OPTIONS[0].value,
              userId: users?.[0]?.id,
            }
          }
          onFinish={async (values) => {
          const res= addSpaceUserUsingPost({
              ...values,
              spaceId:spaceId
            })
            onSubmit?.({
              ...values,
              spaceId: spaceId,
            });
            return;
          }}
        >
          <ProForm.Item label={"协作人"} name={'userId'}>
            <Select defaultValue={users?.[0]?.id} options={users?.map(user => {
              return {
                label: user.userAccount,
                value: user.id
              }
            })}></Select>
          </ProForm.Item>
          <ProForm.Item label={"协作权限"} name={'spaceRole'}>
            <Select defaultValue={SPACE_ROLE_OPTIONS[0].value} options={SPACE_ROLE_OPTIONS} >
            </Select>
          </ProForm.Item>
        </ProForm>
      </div>
    </Modal>
  );
};
export default AddUserToSpaceModal;
